package org.skydiveapp;

import org.skydiveapplibrary.ui.InterfaceManager;
import org.skydiveapplibrary.ui.ViewPagerAdapter;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.Constants;
import org.skydiveapplibrary.repository.SettingsRepository;
import org.skydiveapplibrary.util.RigReminderManager;

import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.View;

public class SkyDiveLog2 extends SherlockFragmentActivity
											implements OnBackStackChangedListener, 
											LogEntryListFragment.onLogEntryEditRequestListener,
											GalleryFragment.onLogEntryEditRequestListener,
											LogEntryEditFragment.onLogEntryEditStatusChangedListener
{
    private boolean isDualDisplay;
    private Bundle requestedLogEntryEditArgs;

    private ViewPagerAdapter viewPagerAdapter;
	private ViewPager mainViewPager;
	private FragmentManager mFragmentManager;
	private String savedSelectedTab;
	
    private static final int LOG_ENTRY_EDIT_REPLY_CLOSED = 10;
    private static final int LOG_ENTRY_EDIT_REPLY_UPDATABLE = 20;
 
    private static final int REQUEST_LOG_ENTRY_EDIT = 10;
    
    private SettingsRepository settingsRepository;
    
	@Override 
	public void onCreate(Bundle savedInstanceState)
	{ 
		super.onCreate(savedInstanceState);
		
		// Set the preference defaults
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

		
		settingsRepository = new SettingsRepository(this);
		if (settingsRepository.getUseLightTheme())
			setTheme(R.style.SkydiveAppTheme_Light);
		
		// show main view
		setContentView(R.layout.main);
		
		savedSelectedTab = null;
		if (savedInstanceState != null)
			savedSelectedTab = savedInstanceState.getString("SelectedTab");
		
		// if the left frame is present the tablet view must be in use
		View logEntryLeftView = findViewById(R.id.leftFrame);
		isDualDisplay = (logEntryLeftView != null);
		
		mainViewPager = (ViewPager) this.findViewById(R.id.viewPager);
		mFragmentManager = getSupportFragmentManager();
		
		if (mainViewPager.getAdapter() == null)
			viewPagerAdapter = new ViewPagerAdapter(this, mainViewPager);
		else
		{
			viewPagerAdapter = (ViewPagerAdapter) mainViewPager.getAdapter();
			viewPagerAdapter.Clear();
		}
		
		mFragmentManager.addOnBackStackChangedListener(this);
		
		// Add summary view
		Bundle pageBundle = new Bundle();
		pageBundle.putString("Title", getString(R.string.main_summary_tab_label).toUpperCase());
		pageBundle.putString("Tag", Constants.TAG_SUMMARY);
		viewPagerAdapter.addFrag(new SummaryActivity(), pageBundle);

		if (isDualDisplay) // TABLET VIEW
		{
			InterfaceManager.getInstance().replaceFragment(mFragmentManager, 
					InterfaceManager.FRAME_LEFT,
                    getLogEntryListFragment(),
                    Constants.TAG_LOG_ENTRY_LIST, false);
	    }
		else // PHONE VIEW
		{						
			pageBundle = new Bundle();
			pageBundle.putString("Title", "JUMP LIST");
			pageBundle.putString("Tag", Constants.TAG_LOG_ENTRY_LIST);
			viewPagerAdapter.addFrag(getLogEntryListFragment(), pageBundle);
		}
		
		pageBundle = new Bundle();
		pageBundle.putString("Title", getString(R.string.main_gear_tab_label).toUpperCase());
		pageBundle.putString("Tag", Constants.TAG_GEAR_LIST);
		viewPagerAdapter.addFrag(new GearListFragment(), pageBundle);
		
		pageBundle = new Bundle();
		pageBundle.putString("Title", getString(R.string.main_more_tab_label).toUpperCase());
		pageBundle.putString("Tag", Constants.TAG_MORE);
		viewPagerAdapter.addFrag(new MoreActivity(), pageBundle);

		pageBundle = new Bundle();
		pageBundle.putString("Title", getString(R.string.main_gallery_tab_label).toUpperCase());
		pageBundle.putString("Tag", Constants.TAG_GALLERY);
		viewPagerAdapter.addFrag(new GalleryFragment(), pageBundle);

		// check rig reminders
		RigReminderManager.getInstance().showRigReminderAlert(this);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();

		if (savedSelectedTab == Constants.TAG_GEAR_LIST)
		{
			mainViewPager.setCurrentItem(isDualDisplay ? 1 : 2);
		}
		else if (savedSelectedTab == Constants.TAG_MORE)
		{
			mainViewPager.setCurrentItem(isDualDisplay ? 2 : 3);
		}
		else if (savedSelectedTab == Constants.TAG_GALLERY)
		{
			mainViewPager.setCurrentItem(isDualDisplay ? 3 : 4);
		}
		else if (savedSelectedTab == Constants.TAG_SUMMARY)
		{
			mainViewPager.setCurrentItem(isDualDisplay ? 0 : 1);
		}
		else if (savedSelectedTab == Constants.TAG_LOG_ENTRY_LIST)
		{
			mainViewPager.setCurrentItem(0);
		}
		else if (savedSelectedTab != null && !savedSelectedTab.contentEquals("null"))
		{
			mainViewPager.setCurrentItem(isDualDisplay ? 0 : 1);
		}
		
		savedSelectedTab = "null";
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		super.onWindowFocusChanged(hasFocus);

		if (!isDualDisplay)
			checkIsLogEntryEditFragmentOpen();
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
               
        outState.putString("SelectedTab", 
        		viewPagerAdapter.getTag(mainViewPager.getCurrentItem()));
    }
	
	@Override
	public void onBackPressed()
	{
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		
		if (logEntryEditFragment != null)
		{
			logEntryEditFragment.requestClose();
		}
		else if (logEntryListFragment != null && logEntryListFragment.isSignatureModeEnabled())
		{
			logEntryListFragment.toggleSignMode();
		}
		else
		{
			finish();
			overridePendingTransition(R.anim.hold,
					R.anim.exit_dropout);
		}
	}
	
	// The LogEntryListFragment needs to be moved from one container to another.
	// A remove call must be processed before it can be added to another container.
	private Fragment getLogEntryListFragment()
	{
		Fragment logEntryListFragment = mFragmentManager.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);

		if (logEntryListFragment != null)
		{
			FragmentTransaction ft = mFragmentManager.beginTransaction();
			ft.remove(logEntryListFragment);
			ft.commit();
			mFragmentManager.executePendingTransactions();
		}
		else		
			logEntryListFragment = new LogEntryListFragment();
		
		return logEntryListFragment;
	}

	@Override
	public void onLogEntryEditRequest(Bundle args) {
		
		requestedLogEntryEditArgs = args;
		
		if (isDualDisplay)
		{
			launchLogEntryEditFragment();
		}
		else
		{
			launchLogEntryEditActivity();
		}

	}
	
	private void launchLogEntryEditFragment()
	{
		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (logEntryEditFragment != null)
		{
			if (logEntryEditFragment.requestUpdate())
			{
				logEntryEditFragment.updateContent(requestedLogEntryEditArgs);
				
				if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
					logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
				else
					logEntryListFragment.clearHighlightedRows();
			}
		}
		else
		{
			InterfaceManager.getInstance().replaceFragment(getSupportFragmentManager(),
				InterfaceManager.FRAME_RIGHT,
				LogEntryEditFragment.newInstance(requestedLogEntryEditArgs),
				Constants.TAG_LOG_ENTRY_EDIT, true,
				R.anim.enter_fadein, R.anim.exit_fadeout);
			
			if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
			{
				logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
			}
			else
				logEntryListFragment.clearHighlightedRows();
		}
	}
	
	private void launchLogEntryEditActivity()
	{
		Intent intent = new Intent(this, LogEntryEditActivity.class);
		intent.putExtras(requestedLogEntryEditArgs);
		startActivityForResult(intent, REQUEST_LOG_ENTRY_EDIT);
	}

	@Override
	public void onLogEntryEditStatusChanged(int response)
	{

		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (response == LOG_ENTRY_EDIT_REPLY_CLOSED) //LogEntryEdit closed
		{		
			logEntryListFragment.clearHighlightedRows();
		}
		else if (response == LOG_ENTRY_EDIT_REPLY_UPDATABLE) //LogEntryEdit ready for action
		{
			if (logEntryEditFragment != null)
			{
				logEntryEditFragment.updateContent(requestedLogEntryEditArgs);
			}
			else
			{
				InterfaceManager.getInstance().replaceFragment(mFragmentManager,
					InterfaceManager.FRAME_RIGHT,
					LogEntryEditFragment.newInstance(requestedLogEntryEditArgs),
					Constants.TAG_LOG_ENTRY_EDIT, true,
					R.animator.fadein, R.animator.fadeout);
			}
			
			if (isDualDisplay)
			{
				if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
					logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
				else
					logEntryListFragment.clearHighlightedRows();
			}
		}	
	}
	
	// Called when MainActivity is launched to see if there is a LogEntryEditFragment open
	// If so it will be closed and launched as an activity.
	private void checkIsLogEntryEditFragmentOpen()
	{
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) mFragmentManager
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (logEntryEditFragment != null)
		{
			requestedLogEntryEditArgs = logEntryEditFragment.configureBundle(new Bundle());
			mFragmentManager.popBackStackImmediate();
			
			launchLogEntryEditActivity();
		}
	}
	
	// Called when the LogEntryEditActivity detects its running while in a tablet view.
	// This launches the same window as a fragment.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == REQUEST_LOG_ENTRY_EDIT && resultCode == RESULT_OK)
        {
        	if (isDualDisplay)
        	{
        		requestedLogEntryEditArgs = intent.getExtras();
        		launchLogEntryEditFragment();
        	}
        	else
        	{
        		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) mFragmentManager
        				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
       		
        		if (logEntryListFragment != null)
        		{
        			logEntryListFragment.clearHighlightedRows();
        		}
        	}
        }
        else
        {
        	super.onActivityResult(requestCode, resultCode, intent);
        }
    }

	@Override
	public void onBackStackChanged()
	{
		if (mFragmentManager.getBackStackEntryCount() == 0)
		{
			viewPagerAdapter.showMenus(true);
			if (isDualDisplay)
				InterfaceManager.getInstance().setSubtitleText(getSupportActionBar(), "");
		}
		else
		{
			viewPagerAdapter.showMenus(false);
		}
	}	
}